﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MAPDavy.Entities;
using MAPDavy.BusinessLogic;
using System.IO;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace MAPDavy.WebMVC3.Controllers
{
    public class LogsController : Controller
    {
        public LogsController()
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();
                container.BuildUp(this.GetType(), this);
            }
        }

        [Dependency]
        public ILogBL LogBL { get; set; }
        //
        // GET: /Logs/

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Logs/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Logs/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Logs/Create

        [HttpPost]
        [Authorize(Roles = "admin,secretaria,secretariaPrimaria,secretariaSecundaria")]
        public ActionResult Create(FormCollection collection, HttpPostedFileBase fileLog)
        {
            try
            {
                Log newLog = new Log()
                {
                    Id= 0,
                    MatriculaId = Int32.Parse(collection["Log.MatriculaId"].ToString()),
                    FechaReunion = DateTime.Parse(collection["Log.FechaReunion"].ToString()),
                    Description = collection["Log.Descripcion"].ToString(),
                    Comentario = collection["Log.Comentario"].ToString()
                };

                var studentId = collection["Log.StudentId"].ToString();

                var path = Path.Combine(Server.MapPath("~/files/" + collection["Log.Anio"].ToString() + "/logs" ));

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                if (fileLog != null && fileLog.ContentLength > 0)
                {
                    Random r = new Random(DateTime.Now.Millisecond);
                    int key = r.Next(1000);

                    var key0 = newLog.FechaReunion.Day.ToString() + newLog.FechaReunion.Month.ToString() + newLog.FechaReunion.Year.ToString();

                    var fileName = "log_" + studentId + "_"+ key0 +"_"+key.ToString()+ Path.GetExtension(fileLog.FileName);
                    path = Path.Combine(path, fileName);
                    fileLog.SaveAs(path);

                    newLog.FileName = "~/files/" + collection["Log.Anio"].ToString() + "/logs/" + fileName;
                }

                LogBL.AddLog(newLog);

                return RedirectToAction("Edit", "Alumnos", new { id = collection["Log.MatriculaId"].ToString() });//"#tabs-2"
            }
            catch
            {
                return RedirectToAction("Edit", "Alumnos", new { id = collection["Log.MatriculaId"].ToString() });
            }
        }
        
        //
        // GET: /Logs/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Logs/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Logs/Delete/5
 
        //public ActionResult Delete(int id)
        //{
        //    return View();
        //}

        //
        // POST: /Logs/Delete/5

        [HttpPost]
        [Authorize(Roles = "admin,secretaria,secretariaPrimaria,secretariaSecundaria")]
        public ActionResult Delete(int id)
        {
            try
            {
                var log = LogBL.GetFromLogById(id);

                LogBL.RemoveLog(id);               

                var path = Path.Combine(Server.MapPath(log.FileName));

                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);  
                }

                return Json(true, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
